package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.ServiceSetting;
import com.ybkj.daijia.serverUtils.ServiceUtil;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.SmsTempletContent;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Company.InfoFeeType;
import com.ybkj.daijia.server.model.DriverRebate.DriverRebateType;
import com.ybkj.daijia.server.model.GasRebate;
import com.ybkj.daijia.server.model.GasRebate.GasRebateType;
import com.ybkj.daijia.server.model.MemberRebate;
import com.ybkj.daijia.server.model.MemberRebate.MemberRebateType;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverLevelService;
import com.ybkj.daijia.server.service.DriverRebateService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.GasRebateService;
import com.ybkj.daijia.server.service.MemberRebateService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.SmsService;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "company")
public class CompanyController {

    @Autowired
    private CompanyService companyService;

    @Autowired
    private MemberRebateService memberRebateService;

    @Autowired
    private DriverRebateService driverRebateService;

    @Autowired
    private GasRebateService gasRebateService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private DriverLevelService driverLevelService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private TaskExecutor taskExecutor;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private DriverService driverService;

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public ModelAndView add(HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("companyadd")) {
            ModelAndView mv = new ModelAndView();

            mv.addObject("arealist", areaService.listAll());
            mv.addObject("levellist", driverLevelService.listAll());
            mv.addObject("username", principal.getUsername());

            //等保 不能重复上传
            Long time_token = System.currentTimeMillis();
            //Logo
            req.getSession().setAttribute("upload_img_logo_token", time_token);
//			mv.addObject("upload_img_logo_token", time_token);

            mv.setViewName("company/add");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public String create(Model model, Company company) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("companyadd")) {

            Long companyLimitAmount = 1L;
            try {
                Properties prop = PropertiesLoaderUtils.loadAllProperties("config.properties");
                companyLimitAmount = Long.valueOf(prop.getProperty("company.limit.amount"));
            } catch (Exception e) {
                e.printStackTrace();
            }

            Long totalCount = companyService.countAll();
            if (totalCount >= companyLimitAmount) {
                model.addAttribute("arealist", areaService.listAll());
                model.addAttribute("levellist", driverLevelService.listAll());
                model.addAttribute("username", principal.getUsername());
                model.addAttribute("message", "最多添加" + companyLimitAmount + "家公司");
                return "company/add";
            }

            if (companyNameExists(company.getCompanyName(), null)) {
                model.addAttribute("arealist", areaService.listAll());
                model.addAttribute("levellist", driverLevelService.listAll());
                model.addAttribute("username", principal.getUsername());
                model.addAttribute("message", "公司名称'" + company.getCompanyName() + "'已存在！");
                return "company/add";
            }
            // if(companyWebURLExists(company.getCompanyWebURL(), null)){
            // model.addAttribute("arealist", areaService.listAll());
            // model.addAttribute("levellist", driverLevelService.listAll());
            // model.addAttribute("username", principal.getUsername());
            // model.addAttribute("message","公司网址'"+company.getCompanyWebURL()+"'已存在！");
            // return "company/add";
            // }
            if (abbreviationExists(company.getAbbreviation(), null)) {
                model.addAttribute("arealist", areaService.listAll());
                model.addAttribute("levellist", driverLevelService.listAll());
                model.addAttribute("username", principal.getUsername());
                model.addAttribute("message", "公司简称'" + company.getAbbreviation() + "'已存在！");
                return "company/add";
            }
            if (StringUtils.isNotBlank(company.getAppKey()) && appKeyExists(company.getAppKey(),
                null)) {
                model.addAttribute("arealist", areaService.listAll());
                model.addAttribute("levellist", driverLevelService.listAll());
                model.addAttribute("username", principal.getUsername());
                model.addAttribute("message", "appKey'" + company.getAppKey() + "'已存在！");
                return "company/add";
            }
            company.setCompanyType(false);
            if (StringUtils.isNotBlank(company.getAbbreviation())) {
                company.setAbbreviation(company.getAbbreviation().trim());
            }
            if (StringUtils.isNotBlank(company.getCompanyName())) {
                company.setCompanyName(company.getCompanyName().trim());
            }
            companyService.create(company);

            String detail = "【%s】新增了公司【" + company.getCompanyName() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            return "redirect:list";
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("id") Long id, HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("company")) {
            ModelAndView mv = new ModelAndView();

            Company local = companyService.findOne(id);

            mv.addObject("company", local);
            mv.addObject("arealist", areaService.listAll());
            mv.addObject("levellist", driverLevelService.listAll());
            mv.addObject("username", principal.getUsername());

            //等保 不能重复上传
            Long time_token = System.currentTimeMillis();
            //Logo
            req.getSession().setAttribute("upload_img_logo_token", time_token);
//			mv.addObject("upload_img_logo_token", time_token);

            mv.setViewName("company/edit");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(Model model, Company company, HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("company")) {
            if (companyNameExists(company.getCompanyName(), company.getId())) {
                model.addAttribute("arealist", areaService.listAll());
                model.addAttribute("levellist", driverLevelService.listAll());
                model.addAttribute("username", principal.getUsername());
                model.addAttribute("company", company);
                model.addAttribute("message", "公司名称'" + company.getCompanyName() + "'已存在！");
                return "company/edit";
            }
            // if(companyWebURLExists(company.getCompanyWebURL(),
            // company.getId())){
            // model.addAttribute("arealist", areaService.listAll());
            // model.addAttribute("levellist", driverLevelService.listAll());
            // model.addAttribute("username", principal.getUsername());
            // model.addAttribute("company", company);
            // model.addAttribute("message","公司网址'"+company.getCompanyWebURL()+"'已存在！");
            // return "company/edit";
            // }
            if (abbreviationExists(company.getAbbreviation(), company.getId())) {
                model.addAttribute("arealist", areaService.listAll());
                model.addAttribute("levellist", driverLevelService.listAll());
                model.addAttribute("username", principal.getUsername());
                model.addAttribute("company", company);
                model.addAttribute("message", "公司简称'" + company.getAbbreviation() + "'已存在！");
                return "company/edit";
            }
            if (StringUtils.isNotBlank(company.getAppKey()) && appKeyExists(company.getAppKey(),
                company.getId())) {
                model.addAttribute("arealist", areaService.listAll());
                model.addAttribute("levellist", driverLevelService.listAll());
                model.addAttribute("username", principal.getUsername());
                model.addAttribute("company", company);
                model.addAttribute("message", "appKey'" + company.getAppKey() + "'已存在！");
                return "company/edit";
            }

            Company local = companyService.findOne(company.getId());
            String localAbbreviation = local.getAbbreviation();
            final String newAbbreviation = company.getAbbreviation();
            final Long companyId = company.getId();
            local.setProvName(company.getProvName());
            local.setCityName(company.getCityName());
            local.setAreaId(company.getAreaId());
            local.setAreaCarId(company.getAreaCarId());
            local.setAreaPaotuiId(company.getAreaPaotuiId());
            local.setCompanyAddress(company.getCompanyAddress());
            local.setLongitude(company.getLongitude());
            local.setLatitude(company.getLatitude());
            local.setCompanyName(company.getCompanyName());
            local.setAbbreviation(company.getAbbreviation());
            local.setTelephone(company.getTelephone());
            local.setEmergencyPhone(company.getEmergencyPhone());
            local.setCompanyWebURL(company.getCompanyWebURL());
            local.setManager(company.getManager());
            local.setMobilePhone(company.getMobilePhone());
            local.setFox(company.getFox());
            local.setEmail(company.getEmail());
            local.setScope(company.getScope());
            local.setFzzPhone(company.getFzzPhone());
            local.setMemo(company.getMemo());
            local.setAppKey(company.getAppKey());
            local.setLogo(company.getLogo());
            local.setBdLevelId(company.getBdLevelId());

            String basePath = getBasePath(req);
            companyService.update(local, basePath);

            String detail = "【%s】修改了公司【" + company.getCompanyName() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            if (!localAbbreviation.equals(newAbbreviation)) {
                taskExecutor.execute(new Runnable() {
                    public void run() {
                        try {
                            memberService.changeCompanyAbbreviation(companyId, newAbbreviation);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

            return "redirect:list";
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "sms/{id}", method = RequestMethod.GET)
    public ModelAndView sms(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("smstemplet")) {
            ModelAndView mv = new ModelAndView();

            Company local = companyService.findOne(id);

            mv.addObject("company", local);

            mv.addObject("sms_driverCreate",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.driverCreate));
            mv.addObject("sms_driverChangePassword",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.driverChangePassword));
            mv.addObject("sms_driverMoney",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.driverMoney));
            mv.addObject("sms_memberCode",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.memberCode));
            mv.addObject("sms_driverCode",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.driverCode));
            mv.addObject("sms_newOrder",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.newOrder));
            mv.addObject("sms_cancelOrder",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.cancelOrder));
            mv.addObject("sms_revokeOrder",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.revokeOrder));
            mv.addObject("sms_driverAccept",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.driverAccept));
            mv.addObject("sms_arriveFromPlace",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.arriveFromPlace));
            mv.addObject("sms_orderFinished",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.orderFinished));
            mv.addObject("sms_modifyCash",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.modifyCash));
            mv.addObject("sms_yupaiOrder",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.yupaiOrder));
            mv.addObject("sms_memberRechargeRecord",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.memberRechargeRecord));
            mv.addObject("sms_memberConsumedRecord",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.memberConsumedRecord));
            mv.addObject("sms_activity",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.activity));
            mv.addObject("sms_recharge",
                smsService.findByAlias(local.getId(), SmsTemplet.SmsType.recharge));

            mv.setViewName("company/smstemplet");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "content/{id}", method = RequestMethod.GET)
    public ModelAndView content(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("company")) {
            ModelAndView mv = new ModelAndView();

            Company local = companyService.findOne(id);
            mv.addObject("company", local);
            mv.setViewName("company/feecontent");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "updateContent", method = RequestMethod.POST)
    public String updateContent(Long companyId, String Content, HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("company")) {

            Company local = companyService.findOne(companyId);

            local.setFeeContent(Content);
            String basePath = getBasePath(req);
            companyService.update(local, basePath);

            return "redirect:list";
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "uploadInterface/{id}", method = RequestMethod.GET)
    public ModelAndView uploadInterface(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("company")) {
            ModelAndView mv = new ModelAndView();
            Company company = companyService.findOne(id);

            mv.setViewName("company/uploadInterface");
            mv.addObject("company", company);

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "savepictures", method = RequestMethod.POST)
    public String savepictures(Company company, HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("company")) {
            Company local = companyService.findOne(company.getId());

            local.setPicture(company.getPicture());
            local.setIntroduceTitle(company.getIntroduceTitle());
            local.setIntroduceContent(company.getIntroduceContent());
            String basePath = getBasePath(req);
            companyService.update(local, basePath);

            return "redirect:list";
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "setting/{id}", method = RequestMethod.GET)
    public ModelAndView setting(HttpServletRequest req, @PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("company")) {
            ModelAndView mv = new ModelAndView();
            Company local = companyService.findOne(id);
            Setting setting = settingUtils.get();

            mv.setViewName("company/setting");
            mv.addObject("company", local);
            mv.addObject("isUpPlatformInfo", setting.isUpPlatformInfo());

            /*
             * //短信 mv.addObject("sms_driverCreate",
             * smsService.findByAlias(local
             * .getId(),SmsTemplet.SmsType.driverCreate));
             * mv.addObject("sms_driverChangePassword",
             * smsService.findByAlias(local
             * .getId(),SmsTemplet.SmsType.driverChangePassword));
             * mv.addObject("sms_driverMoney",
             * smsService.findByAlias(local.getId
             * (),SmsTemplet.SmsType.driverMoney));
             * mv.addObject("sms_memberCode",
             * smsService.findByAlias(local.getId(
             * ),SmsTemplet.SmsType.memberCode)); mv.addObject("sms_newOrder",
             * smsService
             * .findByAlias(local.getId(),SmsTemplet.SmsType.newOrder));
             * mv.addObject("sms_cancelOrder",
             * smsService.findByAlias(local.getId
             * (),SmsTemplet.SmsType.cancelOrder));
             * mv.addObject("sms_powerCancelOrder",
             * smsService.findByAlias(local.
             * getId(),SmsTemplet.SmsType.powerCancelOrder));
             * mv.addObject("sms_revokeOrder",
             * smsService.findByAlias(local.getId
             * (),SmsTemplet.SmsType.revokeOrder));
             * mv.addObject("sms_powerRevokeOrder",
             * smsService.findByAlias(local.
             * getId(),SmsTemplet.SmsType.powerRevokeOrder));
             * mv.addObject("sms_driverAccept",
             * smsService.findByAlias(local.getId
             * (),SmsTemplet.SmsType.driverAccept));
             * mv.addObject("sms_arriveFromPlace",
             * smsService.findByAlias(local.getId
             * (),SmsTemplet.SmsType.arriveFromPlace));
             * mv.addObject("sms_orderFinished",
             * smsService.findByAlias(local.getId
             * (),SmsTemplet.SmsType.orderFinished));
             * mv.addObject("sms_modifyCash",
             * smsService.findByAlias(local.getId(
             * ),SmsTemplet.SmsType.modifyCash)); mv.addObject("sms_yupaiOrder",
             * smsService
             * .findByAlias(local.getId(),SmsTemplet.SmsType.yupaiOrder));
             * mv.addObject("sms_memberRechargeRecord",
             * smsService.findByAlias(local
             * .getId(),SmsTemplet.SmsType.memberRechargeRecord));
             * mv.addObject("sms_memberConsumedRecord",
             * smsService.findByAlias(local
             * .getId(),SmsTemplet.SmsType.memberConsumedRecord));
             * mv.addObject("sms_activity",
             * smsService.findByAlias(local.getId(),
             * SmsTemplet.SmsType.activity)); mv.addObject("sms_recharge",
             * smsService
             * .findByAlias(local.getId(),SmsTemplet.SmsType.recharge));
             * mv.addObject("sms_baoxianMember",
             * smsService.findByAlias(local.getId
             * (),SmsTemplet.SmsType.baoxianMember));
             * mv.addObject("sms_baoxianDriver",
             * smsService.findByAlias(local.getId
             * (),SmsTemplet.SmsType.baoxianDriver));
             * mv.addObject("sms_paiPaotuiOrder",
             * smsService.findByAlias(local.getId
             * (),SmsTemplet.SmsType.paiPaotuiOrder));
             * mv.addObject("sms_acceptPaotuiOrder",
             * smsService.findByAlias(local
             * .getId(),SmsTemplet.SmsType.acceptPaotuiOrder));
             * mv.addObject("sms_finishPaotuiOrder",
             * smsService.findByAlias(local
             * .getId(),SmsTemplet.SmsType.finishPaotuiOrder));
             */

            // 客户推荐提成
            MemberRebate memberRebate = memberRebateService.findByCompany(local.getId());
            if (null != memberRebate) {
                mv.addObject("memberRebate", memberRebate);
            } else {
                mv.addObject("memberRebate", new MemberRebate());
            }

//			DriverRebate driverRebate = driverRebateService.findByCompany(local.getId());
//			if (null != driverRebate) {
//				mv.addObject("driverRebate", driverRebate);
//			} else {
//				mv.addObject("driverRebate", new DriverRebate());
//			}

            // 加油推荐提成
            GasRebate gasRebate = gasRebateService.findByCompany(local.getId());
            if (null != gasRebate) {
                mv.addObject("gasRebate", gasRebate);
            } else {
                mv.addObject("gasRebate", new GasRebate());
            }

            //等保 不能重复上传
            Long time_token = System.currentTimeMillis();
            //Logo
            req.getSession().setAttribute("upload_img_logo_token", time_token);

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "saveSetting", method = RequestMethod.POST)
    public String saveSetting(Model model, SmsTempletContent smsTempletContent, Long companyId,
        String feeContent, Long memberRebateId,
        Integer type_member, Integer level_member, String content_member,
        BigDecimal commission1_member, BigDecimal money1_member,
        MemberRebateType memberRebateType1_member, BigDecimal commission2_member,
        BigDecimal money2_member,
        MemberRebateType memberRebateType2_member, BigDecimal commission3_member,
        BigDecimal money3_member,
        MemberRebateType memberRebateType3_member, BigDecimal disposableMoney1_member,
        BigDecimal disposableMoney2_member,
        BigDecimal disposableMoney3_member,

        Long driverRebateId, Integer type_driver, Integer level_driver, String content_driver,
        BigDecimal commission1_driver,
        BigDecimal money1_driver, DriverRebateType driverRebateType1_driver,
        BigDecimal disposableMoney1_driver,

        Long gasRebateId, Integer level_gas, BigDecimal commission1_gas, BigDecimal money1_gas,
        GasRebateType gasRebateType1_gas,
        BigDecimal commission2_gas, BigDecimal money2_gas, GasRebateType gasRebateType2_gas,
        BigDecimal commission3_gas, BigDecimal money3_gas,
        GasRebateType gasRebateType3_gas,

        String picture, String introduceTitle, String introduceContent, String picture2,
        String introduceTitle2, String introduceContent2,
        String agreementEmploy, String agreement, String shareTitle, String shareContent,
        String shareImage, String shareURL, String customTitle,
        String customContent, Company company,
        BigDecimal djxFee, BigDecimal ywxFee, BigDecimal infoFee, InfoFeeType infoFeeType,
        Boolean allowPayRule, Boolean allowDjx, Boolean allowYwx,
        String djxContent, String ywxContent, Integer driver_reward_node,
        Integer member_reward_node,
        HttpServletRequest req) throws Exception {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        ServiceSetting serviceSetting = ServiceUtil.checkOpen();

        if (subject.isPermitted("company")) {

            Company local = companyService.findOne(companyId);

            local.setFeeContent(feeContent);
            local.setAgreement(agreement);
            local.setAgreementEmploy(agreementEmploy);
            local.setShareTitle(shareTitle);
            local.setShareContent(shareContent);
            local.setShareURL(shareURL);
            local.setShareImage(shareImage);

            local.setPicture(picture);
            local.setIntroduceTitle(introduceTitle);
            local.setIntroduceContent(introduceContent);

            local.setPicture2(picture2);
            local.setIntroduceTitle2(introduceTitle2);
            local.setIntroduceContent2(introduceContent2);

            local.setCustomTitle(customTitle);// 设置自定义内容
            local.setCustomContent(customContent);// 设置自定义内容
            local.setLowestWorkVirtual(company.getLowestWorkVirtual());
            local.setDjxFee(djxFee);
            local.setYwxFee(ywxFee);
            local.setInfoFee(infoFee);
            local.setInfoFeeType(infoFeeType);
            local.setAllowPayRule(allowPayRule);
            local.setAllowDjx(allowDjx);
            local.setAllowYwx(allowYwx);
            local.setDjxContent(djxContent);
            local.setYwxContent(ywxContent);

            if (serviceSetting.isZhuanche()) {
                local.setUnifiedSocialCreditCode(company.getUnifiedSocialCreditCode());
                local.setNetAboutcarBusinessLicenseNo(company.getNetAboutcarBusinessLicenseNo());
                local.setBusinessScope(company.getBusinessScope());
                local.setOperatingRegion(company.getOperatingRegion());
                local.setMailingAddress(company.getMailingAddress());
                local.setAdministrativeDivisionNo(company.getAdministrativeDivisionNo());
                local.setAdministrativeDivisionNoArr(company.getAdministrativeDivisionNoArr());
                local.setEconomicTypesOfOperatingHousehold(
                    company.getEconomicTypesOfOperatingHousehold());
                local.setOperatingLicenseValidityPeriodStart(
                    company.getOperatingLicenseValidityPeriodStart());
                local.setOperatingLicenseValidityPeriodEnd(
                    company.getOperatingLicenseValidityPeriodEnd());
                local.setOperatingLicenseIssuingAgency(company.getOperatingLicenseIssuingAgency());
                local.setOperatingLicenseIssuingDate(company.getOperatingLicenseIssuingDate());
                local.setRegisteredCapital(company.getRegisteredCapital());
                local.setRegisteredVehiclesNumber(company.getRegisteredVehiclesNumber());
                local.setRegisteredDriverNumber(company.getRegisteredDriverNumber());
                local.setLegalRepresentative(company.getLegalRepresentative());
                local.setLegalRepresentativeIDCard(company.getLegalRepresentativeIDCard());
                local.setLegalRepresentativePhoto(company.getLegalRepresentativePhoto());
                local.setLegalRepresentativePhone(company.getLegalRepresentativePhone());
                local.setPaymentInstitutionName(company.getPaymentInstitutionName());
                local.setPaymentServiceLicenseNo(company.getPaymentServiceLicenseNo());
                local.setPaymentServiceType(company.getPaymentServiceType());
                local.setServiceCoverageArea(company.getServiceCoverageArea());
                local.setProvisionsDepositoryBank(company.getProvisionsDepositoryBank());
                local.setNetAboutCarCompanyLogo(company.getNetAboutCarCompanyLogo());
                local.setServiceAgenciesNumber(company.getServiceAgenciesNumber());
                local.setServiceAgenciesNumberArr(company.getServiceAgenciesNumberArr());
                local.setServiceAgenciesName(company.getServiceAgenciesName());
                local.setServiceAgenciesCode(company.getServiceAgenciesCode());
                local.setServiceAgenciesAddress(company.getServiceAgenciesAddress());
                local.setServiceAgenciesChargePersonName(
                    company.getServiceAgenciesChargePersonName());
                local.setServiceAgenciesChargePersonPhone(
                    company.getServiceAgenciesChargePersonPhone());
                local.setServiceAgenciesCustodianName(company.getServiceAgenciesCustodianName());
                local.setServiceAgenciesCustodianPhone(company.getServiceAgenciesCustodianPhone());
                local.setAdministrativeMailingAddress(company.getAdministrativeMailingAddress());
                local.setAgencyEmergencyTel(company.getAgencyEmergencyTel());
                local.setAgenctCreateDate(company.getAgenctCreateDate());
            }
            try {
                String basePath = getBasePath(req);
                companyService.update(local, basePath);
            } catch (Exception e) {

                e.printStackTrace();
            }

            if (subject.isPermitted("memberrebate")) {
                // 客户推荐提成
                if (null == memberRebateId) {
                    MemberRebate memberRebate = new MemberRebate();
                    memberRebate.setCompanyId(companyId);
                    memberRebate.setType(type_member);
                    memberRebate.setLevel(level_member);
                    memberRebate.setContent(content_member);
                    memberRebate.setDisposableMoney1(disposableMoney1_member);
                    memberRebate.setDisposableMoney2(disposableMoney2_member);
                    memberRebate.setDisposableMoney3(disposableMoney3_member);
                    memberRebate.setCommission1(commission1_member);
                    memberRebate.setCommission2(commission2_member);
                    memberRebate.setCommission3(commission3_member);
                    memberRebate.setMoney1(money1_member);
                    memberRebate.setMoney2(money2_member);
                    memberRebate.setMoney3(money3_member);
                    memberRebate.setMemberRebateType1(memberRebateType1_member);
                    memberRebate.setMemberRebateType2(memberRebateType2_member);
                    memberRebate.setMemberRebateType3(memberRebateType3_member);
                    memberRebate.setMemberRewardNode(member_reward_node);
                    memberRebateService.save(memberRebate);
                } else {
                    MemberRebate memberRebate = memberRebateService.findOne(memberRebateId);
                    memberRebate.setType(type_member);
                    memberRebate.setLevel(level_member);
                    memberRebate.setContent(content_member);
                    memberRebate.setMemberRewardNode(member_reward_node);
                    if (type_member.equals(0)) {
                        memberRebate.setDisposableMoney1(disposableMoney1_member);
                        memberRebate.setDisposableMoney2(disposableMoney2_member);
                        memberRebate.setDisposableMoney3(disposableMoney3_member);
                    } else if (memberRebate.getType().equals(1)) {
                        memberRebate.setCommission1(commission1_member);
                        memberRebate.setCommission2(commission2_member);
                        memberRebate.setCommission3(commission3_member);
                        memberRebate.setMoney1(money1_member);
                        memberRebate.setMoney2(money2_member);
                        memberRebate.setMoney3(money3_member);
                        memberRebate.setMemberRebateType1(memberRebateType1_member);
                        memberRebate.setMemberRebateType2(memberRebateType2_member);
                        memberRebate.setMemberRebateType3(memberRebateType3_member);
                    }
                    memberRebateService.update(memberRebate);
                }
            }

//				if (subject.isPermitted("driverrebate")) {
//					// 司机推荐提成
//					if (null == driverRebateId) {
//						DriverRebate driverRebate = new DriverRebate();
//						driverRebate.setCompanyId(companyId);
//						driverRebate.setType(type_driver);
//						driverRebate.setLevel(level_driver);
//						driverRebate.setContent(content_driver);
//						driverRebate.setDisposableMoney1(disposableMoney1_driver);
//						driverRebate.setCommission1(commission1_driver);
//						driverRebate.setMoney1(money1_driver);
//						driverRebate.setDriverRebateType1(driverRebateType1_driver);
//						driverRebate.setDriverRewardNode(driver_reward_node);
//						driverRebateService.save(driverRebate);
//					} else {
//						DriverRebate driverRebate = driverRebateService.findOne(driverRebateId);
//						driverRebate.setType(type_driver);
//						driverRebate.setLevel(level_driver);
//						driverRebate.setContent(content_driver);
//                        driverRebate.setDriverRewardNode(driver_reward_node);
//						if (type_driver.equals(0)) {
//							driverRebate.setDisposableMoney1(disposableMoney1_driver);
//						} else if (driverRebate.getType().equals(1)) {
//							driverRebate.setCommission1(commission1_driver);
//							driverRebate.setMoney1(money1_driver);
//							driverRebate.setDriverRebateType1(driverRebateType1_driver);
//						}
//						driverRebateService.update(driverRebate);
//					}
//				}

            if (subject.isPermitted("gasstation")) {
                // 加油推荐提成
                GasRebate gr = gasRebateService.findByCompany(companyId);
                if (null == gasRebateId && gr == null) {
                    GasRebate gasRebate = new GasRebate();
                    gasRebate.setCompanyId(companyId);
                    gasRebate.setLevel(level_gas);
                    gasRebate.setCommission1(commission1_gas);
                    gasRebate.setCommission2(commission2_gas);
                    gasRebate.setCommission3(commission3_gas);
                    gasRebate.setMoney1(money1_gas);
                    gasRebate.setMoney2(money2_gas);
                    gasRebate.setMoney3(money3_gas);
                    gasRebate.setGasRebateType1(gasRebateType1_gas);
                    gasRebate.setGasRebateType2(gasRebateType2_gas);
                    gasRebate.setGasRebateType3(gasRebateType3_gas);
                    gasRebateService.save(gasRebate);
                } else {
                    GasRebate gasRebate = gasRebateService.findOne(gasRebateId);
                    if (gasRebate == null) {
                        gasRebate = gasRebateService.findByCompany(companyId);
                    }
                    gasRebate.setLevel(level_gas);
                    gasRebate.setCommission1(commission1_gas);
                    gasRebate.setCommission2(commission2_gas);
                    gasRebate.setCommission3(commission3_gas);

                    gasRebate.setMoney1(money1_gas);
                    gasRebate.setMoney2(money2_gas);
                    gasRebate.setMoney3(money3_gas);

                    gasRebate.setGasRebateType1(gasRebateType1_gas);
                    gasRebate.setGasRebateType2(gasRebateType2_gas);
                    gasRebate.setGasRebateType3(gasRebateType3_gas);

                    gasRebateService.update(gasRebate);
                }
            }

            String detail = "【%s】修改了公司设置";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            return "redirect:/company/list";
        } else {
            throw new NoPermissionException();
        }
    }

    private boolean companyNameExists(String companyName, Long id) {
        Company company = companyService.findByCompanyName(companyName);
        if (null != company) {
            if (null != id && id.equals(company.getId())) {
                return false;
            }
            return true;
        }
        return false;
    }

    private boolean companyWebURLExists(String companyWebURL, Long id) {
        Company company = companyService.findByCompanyWebURL(companyWebURL);
        if (null != company) {
            if (null != id && id.equals(company.getId())) {
                return false;
            }
            return true;
        }
        return false;
    }

    private boolean abbreviationExists(String abbreviation, Long id) {
        Company company = companyService.findByAbbreviation(abbreviation);
        if (null != company) {
            if (null != id && id.equals(company.getId())) {
                return false;
            }
            return true;
        }
        return false;
    }

    private boolean appKeyExists(String appKey, Long id) {
        Company company = companyService.findByAppKey(appKey);
        if (null != company) {
            if (null != id && id.equals(company.getId())) {
                return false;
            }
            return true;
        }
        return false;
    }

    @RequestMapping("list")
    public ModelAndView list() {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("company")) {
            ModelAndView mv = new ModelAndView();

            mv.setViewName("company/list");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping("listData")
    public @ResponseBody
    Page<Company> listData(@RequestParam(required = false, value = "name") String name) {

        Subject subject = SecurityUtils.getSubject();
        // if (subject.isPermitted("company")) {
        Page<Company> page = companyService.queryAll(name);
        for (Company company : page.getContent()) {
            company.setArea(areaService.findOne(company.getAreaId()));
            company.setAreaCar(areaService.findOne(company.getAreaCarId()));
        }
        return page;
        // } else {
        // throw new NoPermissionException();
        // }

    }

    @RequestMapping("listAllData")
    public @ResponseBody
    List<Company> listAllData(@RequestParam(required = false, value = "name") String name) {

        Subject subject = SecurityUtils.getSubject();

        // if (subject.isPermitted("company")) {
        List<Company> list = companyService.queryAllData(name);
        // for (Company company : list) {
        // company.setArea(areaService.findOne(company.getAreaId()));
        // company.setAreaCar(areaService.findOne(company.getAreaCarId()));
        // }
        return list;
        // } else {
        // throw new NoPermissionException();
        // }

    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }


    private String getBasePath(HttpServletRequest req) {

        try {
            return WebUtils.getRealPath(req.getSession().getServletContext(), "/");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return StringUtils.EMPTY;
    }

}
